import {FC, useEffect, useState} from "react";
import './styles/OnlineUsers.css'
import {getUserById} from "../../../../http/userApi";
import {getImageById} from "../../../../http/imageApi";
import UserInfo from "../../../../models/UserInfo";
import handleImageNotLoaded from "../../../../functions/handleImageNotLoaded";
import routeNames from "../../../../utils/routeNames";
import {useNavigate} from "react-router-dom";

interface OnlineUsersProps {
    onlineUsers: string[];
}

const OnlineUsers: FC<OnlineUsersProps> = ({onlineUsers}) => {
    const [users, setUsers] = useState<(UserInfo | undefined)[]>([]);
    const navigate = useNavigate()

    useEffect(() => {
        const fetchUsers = async () => {
            const fetchedUsers = await Promise.all(onlineUsers.map(async (userId) => {
                const user = await getUserById(userId);
                if (user)
                    return user;
            }));
            setUsers(fetchedUsers);
        };

        fetchUsers().catch(error => console.error("Ошибка при загрузке пользователей онлайн", error));
    }, [onlineUsers]);

    return (
        <div className="online-users-container">
            <div className="online-users-header">
                <h1>Online Users</h1>
            </div>
            <ul className="online-users-list">
                {users && users.map((userInfo: UserInfo | undefined, index) => (
                    userInfo && <li key={index} className="user-item"
                                    onClick={() => navigate(routeNames.USER_PAGE, {state: {userInfoId: userInfo.userInfoId}})}>
                        <img src={getImageById(userInfo.imageId)} alt="User Avatar" className="user-avatar"
                             onError={handleImageNotLoaded}/>
                        <span className="user-username">{userInfo.userName}</span>
                    </li>
                ))}
            </ul>
        </div>
    );
};

export default OnlineUsers;